package com.linyaonan.leetcode.medium._102;


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 给定一个二叉树，返回其按层次遍历的节点值。 （即逐层地，从左到右访问所有节点）。
 * <p>
 * 例如:
 * 给定二叉树: [3,9,20,null,null,15,7],
 * <p>
 * 3
 * / \
 * 9  20
 * /  \
 * 15   7
 * 返回其层次遍历结果：
 * <p>
 * [
 * [3],
 * [9,20],
 * [15,7]
 * ]
 *
 * @author: Lin
 * @date: 2020/1/18
 */
public class BinaryTreeLevelOrderTraversal {
    Queue<Integer> indexList;
    Queue<TreeNode> nodeList;
    List<List<Integer>> result;

    public List<List<Integer>> levelOrder(TreeNode root) {
        // 初始化
        indexList = new LinkedList<>();
        nodeList = new LinkedList<>();
        result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        indexList.add(0);
        nodeList.add(root);
        List<Integer> first = new ArrayList<>();
        result.add(first);
        while (nodeList.size() != 0) {
            TreeNode node = nodeList.poll();
            Integer index = indexList.poll();
            List<Integer> saved = result.get(index);
            if (node != null) {
                saved.add(node.val);
                index++;
                if (node.left != null) {
                    nodeList.add(node.left);
                    indexList.add(index);
                }
                if (node.right != null) {
                    nodeList.add(node.right);
                    indexList.add(index);
                }
                if (node.left != null || node.right != null) {
                    if (index > result.size() - 1) {
                        List<Integer> add = new ArrayList<>();
                        result.add(index, add);
                    }
                }
            }
        }
        return result;
    }

    public List<List<Integer>> levelOrder2(TreeNode root) {
        // 1. 边界情况
        if (root == null) {
            return new ArrayList<>();
        }
        // 2. 将root放入到数组里面
        LinkedList<TreeNode> list = new LinkedList<>();
        list.add(root);

        ArrayList<List<Integer>> result = new ArrayList<>();
        ArrayList<Integer> head = new ArrayList<>();
        head.add(root.val);
        result.add(head);

        while (!list.isEmpty()) {
            LinkedList<TreeNode> temp = new LinkedList<>();
            ArrayList<Integer> add = new ArrayList<>();
            for (TreeNode treeNode : list) {
                if (treeNode.left != null) {
                    temp.add(treeNode.left);
                    add.add(treeNode.left.val);
                }
                if (treeNode.right != null) {
                    temp.add(treeNode.right);
                    add.add(treeNode.right.val);
                }
            }
            if (!add.isEmpty()) {
                result.add(add);
            }
            list = temp;
        }

        return result;
    }
}
